const Koa = require("koa");
const KoaRouter = require("@koa/router");
const jwt = require("jsonwebtoken");

const app = new Koa();
const userRouter = new KoaRouter({ prefix: "/users" });

const secretKey = "secretaaabbbbcccc";

userRouter.get("/login", (ctx) => {
  const payload = { id: 111, name: "allfocuse" };
  const token = jwt.sign(payload, secretKey, { expiresIn: "1h" }); // 生成token
  ctx.body = {
    code: 0,
    token,
    message: "登录成功",
  };
});

userRouter.get("/list", (ctx, next) => {
  const authorization = ctx.headers.authorization;
  const token = authorization.replace("Bearer ", "");
  console.log(token);

  try {
    const result = jwt.verify(token, secretKey); // 验证token

    ctx.body = {
      code: 0,
      data: [{ id: 1, name: "allfocuse" }], // 验证成功返回数据
    };
  } catch (err) {
    ctx.body = {
      code: -1010,
      message: "token过期",
    };
  }
});

app.use(userRouter.routes()), app.use(userRouter.allowedMethods());

app.listen(8000, () => {
  console.log("服务器启动成功");
});
